package com.hooper.dp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooper.dp.dto.*;
import com.hooper.dp.entity.User;
import com.hooper.dp.exception.BusinessException;
import com.hooper.dp.mapper.UserMapper;
import com.hooper.dp.service.IUserService;
import com.hooper.dp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hooper.dp.constant.UserConstant.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //参数校验
        if (loginForm == null) {
            throw new BusinessException("参数为空！");
        }
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        String password = loginForm.getPassword();
        if (RegexUtils.isPhoneInvalid(phone)) {
            throw new BusinessException("invalidate phone!");
        }
        if (StrUtil.isAllNotBlank(code, password)) {
            throw new BusinessException("please input the code or password!");
        }
        String cacheCode = stringRedisTemplate.opsForValue().get(USER_CODE_KEY_PREFIX + phone);
        //校验验证码
        if (StringUtils.isNotBlank(code) && !Objects.equals(code, cacheCode)) {
            throw new BusinessException("wrong code!");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = this.getOne(wrapper);
        //若用户不存在，将用户信息存入
        if (user == null) {
            user = createUser(phone);
        }
        //脱敏：
        UserDTO dto = new UserDTO();
        BeanUtil.copyProperties(user, dto);
        //使用UUID生成Token，作为key缓存
        String token = UUID.randomUUID().toString();
        Map<String, Object> userDtoMap = BeanUtil.beanToMap(dto,
                new HashMap<>(), CopyOptions.create()
                        .ignoreNullValue()
                        .setFieldValueEditor((fName, fValue) -> fValue.toString()));
        //将用户信息以Hash的方式存入redis
        stringRedisTemplate.opsForHash().putAll(USER_INFO_CACHE + token, userDtoMap);
        //设置token过期时间为30分钟
        stringRedisTemplate.expire(USER_INFO_CACHE + token, TOKEN_TTL, TimeUnit.MINUTES);
        log.info("登录用户信息：{}", dto);
        //返回token
        return Result.ok(token);
    }

    public User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("用户" + phone + RandomUtil.randomString(4));
        save(user);
        return user;
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1. 判断手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            throw new BusinessException("手机号格式错误！");
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3. 将验证码信息存入redis中
        stringRedisTemplate.opsForValue().set(USER_CODE_KEY_PREFIX + phone, code,CODE_TTL,TimeUnit.MINUTES);
        //4.发送验证码
        log.info("验证码：{}", code);
        return Result.ok(code);
    }
}
